package client.comm.commlib

import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.os.Environment
import androidx.core.net.toUri
import client.comm.commlib.utils.SharedUtil
import client.comm.snackbar.SnackBarActivity
import java.lang.ref.WeakReference


class ContextProvider private constructor() {

    private var ctx: WeakReference<Activity>? = null
    private var ctxActivity: WeakReference<Activity>? = null

    companion object {
        private val instant by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { ContextProvider() }

        fun get() = instant
    }

    var logout: ((activity: Activity?) -> Unit)? = null

    fun attach(activity: Activity, logout: ((activity: Activity?) -> Unit)?) {
        if(activity !is SnackBarActivity){
            this.logout = logout
            ctx = WeakReference(activity)
        }
    }

    fun attachPay(activity: Activity, logout: ((activity: Activity?) -> Unit)?) {
        if(activity !is SnackBarActivity){
            this.logout = logout
            ctxActivity = WeakReference(activity)
        }
    }

    fun detach() {
        ctx = null
    }

    fun logoutRun() {
        SharedUtil.clear("token")
        logout?.invoke(activity)
    }

    val activity: Activity?
        get() = ctx?.get()

    val shared: SharedPreferences?
        get() {
            return activity?.getSharedPreferences("zyp_share", Context.MODE_PRIVATE)
        }

    val apkPath: String by lazy {
        var bbb = ""
        activity?.run {
            bbb =
                getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!.absolutePath + "update.apk"
        }
        bbb
    }
}